import 'dart:io';
import 'dart:math';

import 'package:dio/dio.dart';
import 'package:identification_photo/config/constants.dart';
import 'package:identification_photo/model/error_message_model.dart';
import 'package:identification_photo/network/core/response_exception.dart';

/// 格式化工具类
class FormatUtil {
  ///格式化url,将post和get请求以get链接输出
  static String formattedUrl(params) {
    var urlParamsStr = "";
    if (params?.isNotEmpty ?? false) {
      var tempArr = [];
      params.forEach((k, v) {
        tempArr.add(k + '=' + v.toString());
      });
      urlParamsStr = tempArr.join('&');
    }
    return urlParamsStr;
  }

  ///格式化Dio返回的Error
  ///[e] catch到的error
  static ErrorMessageModel dioErrorFormat(e) {
    int? errorCode;
    StateErrorType errorType = StateErrorType.defaultError;
    String errMsg = "网络离家出走了~";

    ///判断一下抛出的异常是不是DIO包裹的异常
    if (e is DioError) {
      ///是不是各种超时
      if (e.type == DioErrorType.receiveTimeout ||
          e.type == DioErrorType.sendTimeout ||
          e.type == DioErrorType.receiveTimeout) {
        errorType = StateErrorType.networkTimeoutError;
        errMsg = "连接超时了";
      } else if (e.type == DioErrorType.response) {
        ///访问出的各种错
        errorType = StateErrorType.responseException;
        errMsg = _getNumberMeans(e);
      } else if (e.type == DioErrorType.cancel) {
        errMsg = e.message;
      } else {
        dynamic otherError = e.error;
        dynamic otherE;
        if (otherError is DioError) {
          otherE = otherError.error;
        }
        if (otherE is ResponseException) {
          errorType = StateErrorType.responseException;
          errMsg = otherE.errorMessage ?? "";
          errorCode = otherE.errorCode;
        } else if (otherE is UnauthorizedError) {
          errorType = StateErrorType.unauthorizedError;
          errMsg = otherE.errorMessage;
          errorCode = otherE.errCode;
        } else if (otherE is SocketException) {
          errorType = StateErrorType.networkTimeoutError;
          errMsg = "网络无连接,请检查网络设置";
        } else {
          errorType = StateErrorType.defaultError;
          errMsg = "出现未知问题";
        }
      }
    } else {
      errorType = StateErrorType.defaultError;
      errMsg = "出问题了~~~";
    }
    return ErrorMessageModel(
        errorType: errorType, message: errMsg, errorCode: errorCode);
  }

  ///获取到的数值转换成文字
  static String _getNumberMeans(DioError e) {
    String str;
    if (e.response?.statusCode != null) {
      switch (e.response?.statusCode) {
        case 400:
          str = "[${e.response?.statusCode}] 参数有误";
          break;
        case 402:
          str = "[${e.response?.statusCode}] 啊 这是一个非法请求呢";
          break;
        case 403:
          str = "[${e.response?.statusCode}] 服务器拒绝请求";
          break;
        case 404:
          str = "[${e.response?.statusCode}] 访问地址不存在";
          break;
        case 405:
          str = "[${e.response?.statusCode}] 请求方式错误";
          break;
        case 500:
          str = "[${e.response?.statusCode}] 服务器内部出错了";
          break;
        case 502:
          str = "[${e.response?.statusCode}] 无效的请求哦";
          break;
        case 503:
          str = "[${e.response?.statusCode}] 服务器说他在忙";
          break;
        case 505:
          str = "[${e.response?.statusCode}] 不支持的HTTP协议";
          break;
        default:
          str = "[${e.response?.statusCode}] 未知错误";
          break;
      }
    } else {
      str = e.message;
    }
    return str;
  }

  ///格式化数字 如果小数后面为0则不显示小数点
  ///[num]要格式化的数字 double 类型
  /// [position] 保留几位小数 int类型
  static formatNum({required double num, required int position}) {
    String numStr = num.toString();
    int dotIndex = numStr.indexOf(".");

    ///当前数字有小数且需要小数位数小于需要的 直接返回当前数字
    if (num % 1 != 0 && (numStr.length - 1 - dotIndex < position)) {
      return numStr;
    }
    int numbs = pow(10, position).toInt();

    ///模运算 取余数
    double remainder = num * numbs % numbs;

    ///小数点后位数如果小于0则表示只保留整数,余数小于1不会进位防止出现200.01保留一位小数出现200.0的情况
    if (position > 0 && remainder >= 0.5) {
      return num.toStringAsFixed(position);
    }
    return num.toStringAsFixed(0);
  }

  /// 将文件大小 格式化
  /// [fileSize] 文件大小
  /// [position] 保留几位小数
  /// [scale] 比例 1000/1024
  /// [specified] 0-5 指定的单位 0是B 1是KB 2是mb 3是GB 4是TB 5是PB
  static String formatFileSize(fileSize,
      {position = 2, scale = 1024, specified = -1}) {
    double num = 0;
    if (fileSize is String) {
      num = double.parse(fileSize);
    } else if (fileSize is int || fileSize is double) {
      num = fileSize;
    }

    ///获取他的单位
    if (num > 0) {
      int unit = log(num) ~/ log(scale);
      if (specified >= 0 && specified < sizeUnit.length) {
        unit = specified;
      }
      double size = num / pow(scale, unit);
      String numStr = formatNum(num: size, position: position);
      return numStr + " " + sizeUnit[unit];
    }
    return "0 B";
  }

  ///数字转成Int
  ///[number] 可以是String 可以是int 可以是double 出错了就返回0;
  static num2int(number) {
    try {
      if (number is String) {
        return int.parse(number);
      } else if (number is int) {
        return number;
      } else if (number is double) {
        return number.toInt();
      } else {
        return 0;
      }
    } catch (e) {
      return 0;
    }
  }

  ///数字转成double
  ///[number] 可以是String 可以是int 可以是double 出错了就返回0;
  static num2double(number) {
    try {
      if (number is String) {
        return double.parse(number);
      } else if (number is int) {
        return number.toDouble();
      } else if (number is double) {
        return number;
      } else {
        return 0.0;
      }
    } catch (e) {
      return 0.0;
    }
  }
}
